<template>

    <div>
        <el-breadcrumb separator="/" style="color: black;font-weight: 700">
            <el-breadcrumb-item >首页</el-breadcrumb-item>
            <el-breadcrumb-item>航班变更</el-breadcrumb-item>
            <el-breadcrumb-item>变更历史</el-breadcrumb-item>
        </el-breadcrumb>
        <h1>航班航线变更历史</h1>
        <!--      搜索表单-->
        <el-row :gutter="20">

            <el-col :span="6">
                <el-form-item label="新始发地" >
                    <el-input placeholder="新始发地" v-model="searchCriteria.NAPCD1" clearable />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="新经停站" >
                    <el-input placeholder="新经停站" v-model="searchCriteria.NAPCD2" clearable />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="新目的站" >
                    <el-input placeholder="新目的站" v-model="searchCriteria.NAPCD3" clearable />
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item>
                    <el-button type="primary" @click="searchOnSubmit">查询</el-button>
                    <el-button @click="searchOnReset">取消</el-button>
                </el-form-item>
            </el-col>
        </el-row>

        <el-table :data="tableData" style="width: 100%">
            <el-table-column
                    :prop="item.prop"
                    :label="item.label"
                    v-for="(item, index) in tableHeader"
                    :key="item.prop"
            >
                <template #default="scope">
                    <div
                            v-show="item.editable || scope.row.editable"
                            class="editable-row"
                    >
                        <template v-if="item.type === 'input'">
                            <el-input
                                    v-bind="{ readonly: ['ID', 'FLID'].includes(item.prop) && scope.row.editable }"
                                    size="small"
                                    v-model="scope.row[item.prop]"
                                    :placeholder="`请输入${item.label}`"
                                    @change="handleEdit(scope.$index, scope.row)"
                            />
                        </template>
                        <template v-if="item.type === 'date'">
                            <el-date-picker
                                    v-model="scope.row[item.prop]"
                                    type="datetime"
                                    value-format="YYYY-MM-DD HH:mm:ss"
                                    :placeholder="`请输入${item.label}`"
                                    @change="handleEdit(scope.$index, scope.row)"
                            />
                        </template>


                    </div>
                    <div
                            v-show="!item.editable && !scope.row.editable"
                            class="editable-row"
                    >
                        <span class="editable-row-span">{{ scope.row[item.prop] }}</span>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页组件示例 -->
        <el-pagination
                background
                layout="prev, pager, next"
                :total="totalElements"
                :current-page="currentPage"
                :page-size="pageSize"
                @current-change="handlePageChange"
                style="margin-top: 20px;"
                v-if="showPagination"
        />
    </div>
</template>


<script setup>
    import { ref, reactive, onMounted,onUpdated,computed,nextTick } from 'vue';
    import {ElMessage, ElMessageBox} from 'element-plus'
    import axios from 'axios'; // 确保已导入axios

    const item = reactive({
        META_ID: "",
        APNO1: "",
        APNO2: "",
        APNO3: "",
        APCD1: "",
        APCD2: "",
        APCD3: "",
        NAPCD1: "",
        NAPCD2:"",
        NAPCD3: "",
        STATU: "",
    });

    const header = {
        prop: "key",
        label: "自定义",
        editable: false,
        type: "input",
    };

    const tableHeader = ref([
        {
            prop: "META_ID",
            label: "航班号",
            editable: false,
            type: "input"
        },
        {
            prop: "APCD1",
            label: "上次未修改的始发地",
            editable: false,
            type: "input"
        },
        {
            prop: "APCD2",
            label: "上次未修改的经停站",
            editable: false,
            type: "input"
        },
        {
            prop: "APCD3",
            label: "上次未修改的目的站",
            editable: false,
            type: "input"
        },
        {
            prop: "NAPCD1",
            label: "修改后的始发站",
            editable: false,
            type: "input"
        },
        {
            prop: "NAPCD2",
            label: "修改后的经停站",
            editable: false,
            type: "input"
        },
        {
            prop: "NAPCD3",
            label: "修改后的目的站",
            editable: false,
            type: "input"
        },
        {
            prop: "STATU",
            label: "状态",
            editable: false,
            type: "input"
        },
    ]);

    const tableData = ref([]);


    const showPagination = ref(true);

    //模糊查询
    const searchCriteria = reactive({

        NAPCD1: "",
        NAPCD2:"",
        NAPCD3: "",
    });

    //分页相关状态
    const currentPage = ref(1); // 当前页码，默认为第一页
    const pageSize = ref(10); // 每页显示数量，默认为5条
    const totalElements = ref(0);

    // 初始化时加载第一页数据
    onMounted(() => {
        fetchFlightData();
        showPagination.value = true;
    });
    onUpdated(() => {
    });

    // 添加分页导航的处理函数，比如上一页、下一页、跳转到特定页
    function handlePageChange(page) {
        currentPage.value = page;
        fetchFlightData(page);
    }


    // 更新fetchUserData函数以支持分页查询
    async function fetchFlightData(current = currentPage.value, size = pageSize.value) {
        try {
            const response = await axios.get('/flightHistory/getAll', {
                params: {
                    currentPage: current,
                    pageSize: size
                }
            });
            if (!response.data.errorCode || response.data.errorCode === "200") {
                // 直接在映射过程中进行过滤和结构转换
                tableData.value = response.data.data
                    // 筛选STATU为"审核通过"的记录
                    .filter(flightView => flightView.statu == "审核通过" || flightView.statu == "审核拒绝")
                    // 映射并使用reactive包装每个对象以支持响应式
                    .map(flightView => reactive({
                        //如果STATU是审核通过就展示该条记录否者不展示
                        META_ID: flightView.metaid,
                        APCD1: flightView.apcd1,
                        //apcd2如果是空，就展示'无'
                        APCD2: flightView.apcd2 ? flightView.apcd2 : '无',
                        // APCD2: flightView.apcd2,
                        APCD3: flightView.apcd3,
                        NAPCD1: flightView.napcd1,
                        NAPCD2: flightView.napcd3 ? flightView.napcd3 : '无',
                        NAPCD3: flightView.napcd2 ? flightView.napcd2 : '无',
                        STATU: flightView.statu,
                        editable: false,
                    }));

                totalElements.value = response.data.total;
            } else {
                ElMessage.error(response.data.msg || '获取数据失败');
                console.error('Failed to fetch data. ErrorCode:', response.data.errorCode, ', Message:', response.data.msg);
            }
        } catch (error) {
            ElMessage.error('获取数据过程中发生错误');
            console.error('Error fetching data:', error);
        }
    }

    // 搜索条件
    async function searchOnSubmit() {
        //NAPCD1NAPCD2NAPCD3只能是数字和字母，可以为空
        if (!/^[a-zA-Z0-9]*$/.test(searchCriteria.NAPCD1) || !/^[a-zA-Z0-9]*$/.test(searchCriteria.NAPCD2) || !/^[a-zA-Z0-9]*$/.test(searchCriteria.NAPCD3)) {
            ElMessage.error('NAPCD1、NAPCD2、NAPCD3只能是数字和字母');
            return;
        }

        try {
            const response = await axios.get(`/flightHistory/find`, {
                params: {
                    NAPCD1: searchCriteria.NAPCD1,
                    NAPCD2: searchCriteria.NAPCD2,
                    NAPCD3: searchCriteria.NAPCD3,
                    currentPage: currentPage.value,
                    pageSize: pageSize.value
                },
            });

            if (response.data.errorCode === "200") {
                // 直接在映射过程中进行过滤和结构转换
                tableData.value = response.data.data
                    // 筛选STATU为"审核通过"的记录
                    .filter(flightView => flightView.statu == "审核通过" || flightView.statu == "审核拒绝")
                    // 映射并使用reactive包装每个对象以支持响应式
                    .map(flightView => reactive({
                        //如果STATU是审核通过就展示该条记录否者不展示
                        META_ID: flightView.metaid,
                        APCD1: flightView.apcd1,
                        //apcd2如果是空，就展示'无'
                        APCD2: flightView.apcd2 ? flightView.apcd2 : '无',
                        // APCD2: flightView.apcd2,
                        APCD3: flightView.apcd3,
                        NAPCD1: flightView.napcd1,
                        NAPCD2: flightView.napcd3 ? flightView.napcd3 : '无',
                        NAPCD3: flightView.napcd2 ? flightView.napcd2 : '无',
                        STATU: flightView.statu,
                        editable: false,
                }));
                //    查询成功后把查询的结果添加到表单展示
                // showPagination.value = false;
            } else {
                ElMessage.error('查询失败，请检查输入或重试');
                console.error('查询失败:', response.data.message || '未提供错误信息');
            }
        } catch (error) {
            ElMessage.error('查询过程中发生错误');
            console.error('查询错误:', error);
        }
    }

    //取消查询
    const searchOnReset = async () => {
        searchCriteria.NAPCD1 = "";
        searchCriteria.NAPCD2 = "";
        searchCriteria.NAPCD3 = "";
        await fetchFlightData();
    };
    //切换表格行进入编辑模式
    function handleEdit(row) {
        row.editable = true;
    }


    // 修改
    async function saveEditedRow(row) {
        try {
            const updatedFlight = {
                id: row.ID,
                flid: row.FLID,
                fide: row.FIDE,
                frtt: row.FRTT,
                frlt: row.FRLT,
            };
            const response = await axios.put(`/view/update`, updatedFlight);

            if (!response.data.errorCode || response.data.errorCode === "200") {
                ElMessage.success('更新成功');
                row.editable = false;
                await fetchFlightData();
            } else {
                ElMessage.error(response.data.msg || '更新失败，请重试');
            }
        } catch (error) {
            console.error('Error updating data:', error);
            ElMessage.error('更新过程中发生错误');
        }
    }
    //取消修改按钮
    const cancelEdit = (row) => {
        row.editable = false;
        //    恢复原来数据
        Object.assign(row, {
            ID: row.ID,
            FLID: row.FLID,
            FIDE: row.FIDE,
            FRTT: row.FRTT,
            FRLT: row.FRLT,
        });
        ElMessage.warning('已取消修改');
        fetchFlightData();
    };
</script>

<style scoped>

</style>